package juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket{

    private int number = 30;

    private Lock lock = new ReentrantLock();

//    public synchronized void sale(){
    public void sale(){


        lock.lock();
        try {
            if (number > 0){
                System.out.println(Thread.currentThread().getName() + "\t卖出第:" + (number--) + "\t还剩:" + (number));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

/**
 *
 * 题目:三个售票员卖出30张票
 *
 * 多线程编程的企业级套路+模板
 * 1,在高内聚低耦合的前提下,线程  操作(对外暴露的调用方法)  资源类
 */
public class SaleTicket {



    public static void main(String args[]){
        Ticket ticket = new Ticket();
//    public Thread(Runnable target, String name) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1;i <= 40;i++){
                    ticket.sale();
                }
            }
        },"A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1;i <= 40;i++){
                    ticket.sale();
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1;i <= 40;i++){
                    ticket.sale();
                }
            }
        },"C").start();
    }

}
